/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "Texture.h"
#include "Hardware.h"
#include <Gluck.h>
#include <logs/Log.h>
#include <gl/GLU.h>

#undef max

namespace liba
{
namespace lib3d
{
namespace hard
{
namespace macx
{

Texture::Texture(Hardware * hardware, int mipmap_levels, const pictureformat::Format & desired_format, int width, int height, int max_texture_size )
:	hard::Texture( mipmap_levels, desired_format, width, height ),
	texture( 0 ),
	dec_scale( 0 ),
	valid_flag( false ),
	locked_data( 0 )
{
	int texture_size = std::max( width, height );
	if( max_texture_size < texture_size )
	{
		dec_scale = (texture_size / max_texture_size) >> 1;
	}

	glGenTextures( 1, &texture );

	if( !texture )
		throw Gluck(__FUNCTION__, "create_internal_texture() failed");
	this->mipmap_levels = 1;
}

Texture::~Texture()
{
	valid_flag = false;

	if( texture )
		glDeleteTextures( 1, &texture );
	texture = 0;
}

void * Texture::lock(int mipmap_level, int * stride)
{
	if( mipmap_level != dec_scale )
		return 0; // Skip :)

	*stride = (width >> dec_scale) * 4;
	locked_data = new unsigned char [ (width >> dec_scale ) * (height >> dec_scale ) * 4 ];
	return locked_data;
}

void Texture::unlock(int mipmap_level)
{
	glBindTexture( GL_TEXTURE_2D, texture );
	int error = gluBuild2DMipmaps( GL_TEXTURE_2D, 4,
		width >> dec_scale, height >> dec_scale,
		GL_RGBA, GL_UNSIGNED_BYTE, locked_data );
	delete [] locked_data; locked_data = 0;
	valid_flag = true;
}

bool Texture::is_valid()
{
	return valid_flag;
}

bool Texture::set_in_hardware(int stage)
{
	glBindTexture( GL_TEXTURE_2D, texture );
	return true;
}

} // namespace macx
} // namespace hard
} // namespace lib3d
} // namespace liba

